// pages/bluetooth-search/bluetooth-search.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        devices:[
            {name:'test1',device_id:'aaaaaa', device_uuid:'bbbbbbb',device_rssi:'-54',checked:false},
            {name:'test2',device_id:'bbbb', device_uuid:'bbbbbbb',device_rssi:'-54',checked:true}
        ],
        isDiscovery: false,
        discoveryMsg: '',
    },

    //#region 

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        if(!this.data.isDiscovery) {
            this.setData({
                devices:[],
                discoveryMsg:'抱歉，没有匹配到符合条件的设备！'
            });
            this.discoveryBlueToothDevices();
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        if(!this.data.isDiscovery) {
            this.setData({
                devices:[],
                discoveryMsg:'抱歉，没有匹配到符合条件的设备！'
            });
            this.discoveryBlueToothDevices();
        }
        // 结束下拉刷新的动作，恢复页面状态
        wx.stopPullDownRefresh() 
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //#endregion

    //#region 界面操作事件
    deviceSelected(event) {
        console.log(event);
        let devices = this.data.devices;
        for(let i =0; i<devices.length; i++) {
            if(devices[i].device_id == event.detail.value) {
                devices[i].checked = true;
            } else {
                devices[i].checked = false;
            }
        }
        this.setData({
            devices:devices
        });
    },

    navToConnect() {
        let app = getApp();
        let device = this.data.devices.find(p=>p.checked == true);
        console.log(device);
        if(device) {
            app.globalData.deviceInfo = device;
            wx.navigateTo({
              url: '/pages/bluetooth-operator/bluetooth-operator',
            });
        }
    },
    //#endregion

    //#region  私有方法
    async checkBlueToothEnabled() {
        try {
            let available = false;
            console.log('查询蓝牙是否开启...');
            await wx.getBluetoothAdapterState()
                        .then((res) =>{
                            console.log('查询蓝牙是否开启完成');
                            available = res.available;
                        });
            console.log('返回蓝牙状态...');           
            return available;
        } catch (error) {
            console.log(error);
            return false;
        }
    },
    /**
     * 开始搜索附近的蓝牙设备
     */
    async discoveryBlueToothDevices() {
        let _this = this;
        let state = await this.enableBlueTooth();
        if(!state) {
            console.log('初始蓝牙失败...');
            wx.showModal({
                title: '系统提示',
                content: '抱歉手机蓝牙未开启，请开启蓝牙后进行搜索！',
                showCancel: false,
                success (res) {
                    // if (res.confirm) {
                    //     console.log('用户点击确定')
                    // } else if (res.cancel) {
                    //     console.log('用户点击取消')
                    // }
                    
                }
            });
        } else {
            //#region 
            // 监听扫描到新设备事件
            wx.onBluetoothDeviceFound((res) => {
                try{
                    let devices = res.devices;
                    console.log('蓝牙外围设备:' + devices.length);
                    console.log(devices);
                    let deviceList = _this.data.devices;
                    for(let i =0; i<devices.length; i++) {
                        if(devices[i].connectable && devices[i].deviceId) {
                            let c = deviceList.find(p=>p.device_id == devices[i].deviceId);
                            if(c) {
                                c.device_rssi = devices[i].RSSI
                            } else {
                                deviceList.push({
                                    name: devices[i].name||devices[i].deviceId,
                                    device_id: devices[i].deviceId,
                                    device_uuid: devices[i].advertisServiceUUIDs[0],
                                    device_rssi:devices[i].RSSI,
                                    checked: false
                                });
                            }
                        }
                    }
                    _this.setData({
                        devices: deviceList
                    });
                }catch(e) {
                    console.log(e);
                }
            });

            // 开始搜索附近的蓝牙外围设备
            try {
                wx.startBluetoothDevicesDiscovery({
                    allowDuplicatesKey: true,
                    success: (res) => {
                        console.log('正在搜寻附近的蓝牙外围设备...');
                        _this.setData({
                            isDiscovery: true,
                            discoveryMsg: '正在搜寻附近的蓝牙外围设备...'
                        });
                    },
                    fail: (res) =>{
                        console.log('startBluetoothDevicesDiscovery调用失败...');
                    }
                });
            } catch(e) {
                console.log(e);
                if(_this.isDiscovery) {
                    wx.stopBluetoothDevicesDiscovery({
                        fail:(res) => {
                            _this.setData({
                                isDiscovery: false
                            });
                            console.log('stopBluetoothDevicesDiscovery调用失败...');
                        },
                        complete:(res) =>{
                            _this.setData({
                                isDiscovery: false
                            });
                            console.log('停止搜寻附近的蓝牙外围设备...');
                        }
                    });
                }
            }

            //搜索10秒，超时停止蓝牙搜索
            setTimeout(()=>{
                wx.stopBluetoothDevicesDiscovery({
                    success: (res) => {
                        let msg = '';
                        if(_this.data.devices.length == 0) {
                            msg = "抱歉，没有匹配到符合条件的设备！";
                        }
                        _this.setData({
                            isDiscovery:false,
                            discoveryMsg:msg
                        });
                        console.log('停止搜寻附近的蓝牙外围设备...');
                    }
                });
            }, 1000 * 10);
           //#endregion
        }
    },

    /**
     * 初始化蓝牙
     */
    async enableBlueTooth() {
        try{
            let state = false;
            await wx.openBluetoothAdapter()
                .then((res)=>{
                    console.log('初始化蓝牙成功',res);
                    state = true;
                });
            return state;
        } catch(error) {
            console.log(error);
            return false;
        }
    }
    
    //#endregion

})